#!/usr/bin/env perl
# /=====================================================================\ #
# |  compileschema                                                      | #
# | Convert test cases to (x)html(5) for visual comparisons             | #
# |=====================================================================| #
# | support tools for LaTeXML:                                          | #
# |  Public domain software, produced as part of work done by the       | #
# |  United States Government & not subject to copyright in the US.     | #
# |---------------------------------------------------------------------| #
# | Bruce Miller <bruce.miller@nist.gov>                        #_#     | #
# | http://dlmf.nist.gov/LaTeXML/                              (o o)    | #
# \=========================================================ooo==U==ooo=/ #

use strict;
use warnings;
use FindBin;
use Getopt::Long qw(:config no_ignore_case);
use Pod::Usage;

our $htmldest = '/local/www/site/htdocs/latexmltest';
our $logdir   = '/tmp/xtest';
our $testdir  = "$FindBin::RealBin/../t";
our $bindir   = "$FindBin::RealBin/../blib/script";
our @TYPES    = ("html4", "xhtml", "html5");
our %TYPE_EXT = (html4 => 'html', xhtml => 'xhtml', html5 => 'html');
#**********************************************************************
# Parse command line

my $identity = "xtest";
my ($verbosity, $force, $help) = (-1, 0, 0);    # start off quieter
my ($timestamp) = (undef);
GetOptions("force" => \$force,
  "quiet"       => sub { $verbosity--; },
  "verbose"     => sub { $verbosity++; },
  "timestamp=s" => \$timestamp,
  "help"        => \$help,
) or pod2usage(-message => $identity, -exitval => 1, -verbose => 0, -output => \*STDERR);
pod2usage(-message => $identity, -exitval => 1, -verbose => 2, -output => \*STDOUT) if $help;

our $makeindex = 0;
our ($HEADER, $FOOTER);
our @testsets = ();

if (@ARGV) {
  $makeindex = 0;
  @testsets  = @ARGV; }
else {
  $makeindex = 1;
  opendir(DIR, $testdir) or die "Couldn't read test directory $testdir: $!";
  # Heuristic: tests worth displaying in html are in own directories whose name
  # corresponds to a test case like 10_expansion.t.
  # Process in order of the number!
  @testsets = map { (/^(?:\d+)_(\w+)\.t$/ && -d "$testdir/$1" ? $1 : ()) } sort readdir(DIR);
  closedir(DIR); }

#**********************************************************************
if (!-d $htmldest) {
  mkdir($htmldest) or die "Couldn't create destination directory $htmldest: $!"; }

our $htmldata = '';

foreach my $set (@testsets) {
  print STDERR "Looking at directory $testdir/$set\n" if $verbosity >= 0;
  if (!opendir(DIR, "$testdir/$set")) {
    warn "Couldn't read test directory $testdir/$set: $!\nSkipping set $set";
    next; }
  my $p;
  my @tests = sort grep { -f "$testdir/$set/$_.xml" }
    map { (($p = $_) =~ s/\.pdf$// ? ($p) : ()) } readdir(DIR);
  closedir(DIR);

  next unless @tests;

  if (!-d "$htmldest/$set") {
    print STDERR "Creating $htmldest/$set\n" if $verbosity >= 0;
    if (!mkdir("$htmldest/$set")) {
      warn "Couldn't create destination directory $htmldest: $!\nSkipping $set"; } }

  $htmldata .= "<tr><th colspan='5' class='testgroup'>$set</th></tr>\n";

  foreach my $test (@tests) {
    my $srcxml = "$testdir/$set/$test.xml";
    my $srcpdf = "$testdir/$set/$test.pdf";
    my @links  = ("<td class='pdf'><a href='$set/$test.pdf'>pdf</a></td>",
      "<td class='xml'><a href='$set/$test.xml'>xml</a></td>");
    my $usesdtd = system('grep', '--quiet', 'DOCTYPE', $srcxml) == 0;
    copy($srcxml, "$htmldest/$set/$test.xml");
    copy($srcpdf, "$htmldest/$set/$test.pdf");
    foreach my $type (@TYPES) {
      my $ext  = $TYPE_EXT{$type};
      my $dest = "$htmldest/$set/$type/$test.$ext";
      push(@links, "<td class='$type'><a href='$set/$type/$test.$ext'>$type</a></td>");
      if ($force || (!-f $dest) || ((-M $srcxml) < (-M $dest))) {
        print STDERR "Converting test case $set/$test ($type)" . ($usesdtd ? " [dtd]" : "") . "\n";
        system("$bindir/latexmlpost",
          ($usesdtd ? ("--novalidate") : ()),
          "--dest=$dest",
          "--log=$logdir/$set-$test-$type.log",
          "--format=$type",
          "--javascript=LaTeXML-maybeMathjax.js",
          (defined $timestamp ? ("--timestamp=$timestamp") : ()),
          ($verbosity > 0     ? map { "--verbose" } 1 .. $verbosity
            : ($verbosity < 0 ? map { "--quiet" } 1 .. -$verbosity
              : ())),
          $srcxml)
          == 0 or warn "Couldn't transform test case $testdir/$set/$type/$test: $!\nSkpping $set/$type/$test"; } }
    $htmldata .= "<tr><td class='testcase'>$test</td> " . join('', @links) . ".</tr>\n"; }
}

if ($makeindex) {
  my $DIR;
  open($DIR, '>', "$htmldest/index.html") or die "Couldn't create $htmldest/index.html: $!";
  print $DIR $HEADER . $htmldata . $FOOTER;
  close($DIR); }

#======================================================================

sub copy {
  my ($src, $dst) = @_;
  if ($force || (!-f $dst) || ((-M $src) < (-M $dst))) {
    print STDERR "Copying $src to $dst\n" if $verbosity >= 0;
    system('cp', $src, $dst) == 0 or warn "Couldn't copy $src to $dst: $!"; }
  return; }

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
BEGIN {
  $HEADER = <<'EOHead';
<!DOCTYPE html>
<html>
<head><title>LaTeXML Tests</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
th { font-weight:bold; }
.testgroup { text-align:left; font-size:120%; font-style:italic; }
.testcase { padding-left:2em; font-weight:bold; }
.pdf { text-align:center; }
.xml { text-align:center; }
</style>
</head>
<body>
<h1>LaTeXML Tests</h1>
<table>
<tr><th class='testcase'>Testcase</th>
    <th class='pdf'>PDF</th>
    <th class='xml'>LaTeXML</th>
    <th colspan='3'>Generated</th></tr>
EOHead

  $FOOTER = <<'EOFoot';
</table>
</body>
EOFoot
}
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
